package games

import (
	"bufio"
	"fmt"
	"log"
	"math/rand"
	"os"
	"strconv"
	"strings"
	"time"
)

/*
	猜数游戏
*/
func Guess() {
	//1. 生成随机数
	seconds := time.Now().Unix()
	rand.Seed(seconds) //用于生成不同的随机数
	target := rand.Intn(100) + 1
	fmt.Println("I've chosen a random number between 1 to 100.")
	fmt.Println("Can you guess it?")
	fmt.Println(target)

	//2. 键盘获取输入
	reader := bufio.NewReader(os.Stdin)

	success := false //设置默认打印失败信息

	//3. 猜数的失败次数最多十次
	for guesses := 0; guesses < 10; guesses++ {
		//4. 获取用户输入的数
		fmt.Println("You have ", 10-guesses, "guesses left.")
		fmt.Println("Make a guess: ")
		input, err := reader.ReadString('\n')
		if err != nil {
			log.Fatal(err)
		}

		//5. 类型转换
		input = strings.TrimSpace(input)
		guess, err := strconv.Atoi(input)
		if err != nil {
			log.Fatal(err)
		}

		if guess < target {
			fmt.Println("Oops. Your guess was LOW.")
		} else if guess > target {
			fmt.Println("Oops. Your guess was HIGH.")
		} else {
			success = true
			fmt.Println("Good Job!")
			break
		}
	}

	if !success {
		fmt.Println("Sorry, you didn't guess my number. It was: ", target)
	}
}
